package com.tenebrous.jestic.compents.interceptor;

import com.tenebrous.jestic.auth.AuthTokenGenerator;
import com.tenebrous.jestic.server.AbstractInstanceContext;
import com.tenebrous.jestic.server.Instance;
import com.tenebrous.jestic.server.ServerInstance;
import io.grpc.*;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.interceptor.GrpcGlobalServerInterceptor;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.Objects;

@Slf4j
@GrpcGlobalServerInterceptor
public class AuthInterceptor implements ServerInterceptor {

    @Autowired
    private AuthTokenGenerator authToken;

    @Resource
    private AbstractInstanceContext abstractInstanceContext;

    private static final String SKIP_TOKEN_METHOD = "com.zy.tenebrous.jestic.proto.connect.ServerAuthorityService.authentic";

    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> serverCall, Metadata metadata, ServerCallHandler<ReqT, RespT> serverCallHandler) {
        String token = metadata.get(Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER));
        String skipTokenMethod = metadata.get(Metadata.Key.of("SKIP_TOKEN_METHOD", Metadata.ASCII_STRING_MARSHALLER));
        if (!SKIP_TOKEN_METHOD.equals(skipTokenMethod)) {
            Instance instance = abstractInstanceContext.initContext(authToken).getInstanceByToken(token);
            if (Objects.isNull(instance)) {
                throw new RuntimeException("token验证失败!");
            }
        }
        // 异步记录访问日志
        // 1、记录实例信息 2、记录访问接口 3、记录
        return Contexts.interceptCall(Context.current(), serverCall, metadata, serverCallHandler);
    }
}

